package exerise;

/**
 * Created by jimmy on 2019/3/13.
 * 将一个给定字符串根据给定的行数，以从上往下、从左到右进行 Z 字形排列。
 * <p>
 * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时，排列如下：
 * <p>
 * L   C   I   R
 * E T O E S I I G
 * E   D   H   N
 * 之后，你的输出需要从左往右逐行读取，产生出一个新的字符串，比如："LCIRETOESIIGEDHN"。
 * <p>
 * 请你实现这个将字符串进行指定行数变换的函数：
 * <p>
 * string convert(string s, int numRows);
 * 示例 1:
 * <p>
 * 输入: s = "LEETCODEISHIRING", numRows = 3
 * 输出: "LCIRETOESIIGEDHN"
 * 示例 2:
 * <p>
 * 输入: s = "LEETCODEISHIRING", numRows = 4
 * 输出: "LDREOEIIECIHNTSG"
 * 解释:
 * <p>
 * L     D     R
 * E   O E   I I
 * E C   I H   N
 * T     S     G
 */
public class Ex6 {

    public static void main(String[] args) {
        String src = "LEETCODEISHIRING";
        Ex6 ex6 = new Ex6();
        String result1 = ex6.convert1(src, 5);
        System.out.println("result1 == " + result1);
        String result = ex6.convert(src, 5);
        System.out.println("result1 == " + result);

    }

    public String convert1(String s, int numRows) {
        if (numRows == 1) return s;
        int len = s.length();
        int range = 2 * numRows - 2;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            int turnFlag = 0;
            for (int j = i; j < len; ) {
                builder.append(s.charAt(j));
                if (i == 0 || i == numRows - 1) {
                    j += range;
                } else {
                    if (turnFlag % 2 == 0) {
                        j += range - 2 * i;
                    } else {
                        j += 2 * i;
                    }
                    turnFlag++;
                }
            }
        }
        return builder.toString();
    }

    //O(n) O(1)
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        int len = s.length();
        int range = 2 * numRows - 2;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < len; j += range) {
                builder.append(s.charAt(i + j));
                if (i != 0 && i != numRows - 1 && j + range - i < len) {
                    builder.append(s.charAt(j + range - i));
                }
            }
        }
        return builder.toString();
    }
}
